package com.jsh.erp.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jsh.erp.base.AjaxResult;
import com.jsh.erp.datasource.entities.ProductionMaterial;
import com.jsh.erp.datasource.entities.ProductionOrder;
import com.jsh.erp.datasource.entities.ProductionProcess;
import com.jsh.erp.datasource.mappers.ProductionMaterialMapper;
import com.jsh.erp.datasource.mappers.ProductionOrderMapper;
import com.jsh.erp.datasource.mappers.ProductionProcessMapper;
import com.jsh.erp.datasource.req.ProductionTaskAddReq;
import com.jsh.erp.datasource.vo.BomMaterialVo;
import com.jsh.erp.datasource.vo.ProductionTaskVo;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.PageUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author : yy
 */
@Service
public class ProductionTaskService {
    @Resource
    private ProductionOrderMapper productionOrderMapper;
    @Resource
    private ProductionMaterialMapper productionMaterialMapper;
    @Resource
    private ProductionProcessMapper productionProcessMapper;

    @Resource
    private UserService userService;

    public List<ProductionTaskVo> select(String orderNumber, String productInfo, String singleDateStart,
                                         String singleDateEnd, String salesOrderNumber, String planCompletionStart,
                                         String planCompletionEnd, String singleStatus, String customerOriginalNumber) {
        PageUtils.startPage();
        return productionOrderMapper.select(orderNumber, productInfo, singleDateStart,
                singleDateEnd, salesOrderNumber, planCompletionStart, planCompletionEnd, singleStatus, customerOriginalNumber);
    }

    @Transactional(rollbackFor = Exception.class)
    public BaseResponseInfo add(ProductionTaskAddReq productionTaskAddReq) throws Exception {
        BaseResponseInfo responseInfo = new BaseResponseInfo();
        try {
            // 保存生产任务主表数据
            ProductionOrder productionOrder = productionTaskAddReq.getProductionOrder();
            productionOrder.setDocumentDate(new Date());
            productionOrder.setOperatorId(userService.getCurrentUser().getId());
            productionOrderMapper.insert(productionOrder);

            Long taskId = productionOrder.getId();

            // 保存所需物料数据
            List<BomMaterialVo> materialList = productionTaskAddReq.getProductionMaterials();
            if (materialList != null && !materialList.isEmpty()) {
                for (BomMaterialVo material : materialList) {
                    ProductionMaterial productionMaterial = new ProductionMaterial();
                    productionMaterial.setProductionOrderId(taskId);
                    productionMaterial.setMaterialBarcode(material.getBomBarCode());
                    productionMaterial.setRequiredQuantity(material.getNum());
                    productionMaterial.setCost(material.getAllPrice());
                    productionMaterial.setRemarks(material.getRemarks());
                    productionMaterialMapper.insert(productionMaterial);
                }
            }

            // 保存生产工序数据
            List<ProductionProcess> processList = productionTaskAddReq.getProductionProcesses();
            if (processList != null && !processList.isEmpty()) {
                for (ProductionProcess process : processList) {
                    ProductionProcess productionProcess = new ProductionProcess();
                    productionProcess.setProductionOrderId(taskId);
                    productionProcess.setExecutionOrder(process.getExecutionOrder());
                    productionProcess.setProcessName(process.getProcessName());
                    productionProcess.setResponsiblePerson(process.getResponsiblePerson());
                    productionProcess.setBillingMethod(process.getBillingMethod());
                    productionProcess.setLaborCost(process.getLaborCost());
                    productionProcess.setRequiredCost(process.getRequiredCost());
                    productionProcess.setPlannedCompletionDate(process.getPlannedCompletionDate());
                    productionProcess.setRemarks(process.getRemarks());
                    productionProcessMapper.insert(productionProcess);
                }
            }
            responseInfo.code = 200;
            responseInfo.data = "保存成功";
            return responseInfo;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public BaseResponseInfo update(ProductionTaskAddReq productionTaskAddReq) {
        BaseResponseInfo responseInfo = new BaseResponseInfo();
        try {
            ProductionOrder productionOrder = productionTaskAddReq.getProductionOrder();
            productionOrderMapper.updateById(productionOrder);
            Long taskId = productionOrder.getId();
            productionMaterialMapper.delete(new LambdaQueryWrapper<ProductionMaterial>().eq(ProductionMaterial::getProductionOrderId, taskId));
            List<BomMaterialVo> materialList = productionTaskAddReq.getProductionMaterials();
            if (materialList != null && !materialList.isEmpty()) {
                for (BomMaterialVo material : materialList) {
                    ProductionMaterial productionMaterial = new ProductionMaterial();
                    productionMaterial.setProductionOrderId(taskId);
                    productionMaterial.setMaterialBarcode(material.getBomBarCode());
                    productionMaterial.setRequiredQuantity(material.getNum());
                    productionMaterial.setCost(material.getAllPrice());
                    productionMaterial.setRemarks(material.getRemarks());
                    productionMaterialMapper.insert(productionMaterial);
                }
            }
            productionProcessMapper.delete(new LambdaQueryWrapper<ProductionProcess>().eq(ProductionProcess::getProductionOrderId, taskId));
            List<ProductionProcess> processList = productionTaskAddReq.getProductionProcesses();
            if (processList != null && !processList.isEmpty()) {
                for (ProductionProcess process : processList) {
                    ProductionProcess productionProcess = new ProductionProcess();
                    productionProcess.setProductionOrderId(taskId);
                    productionProcess.setExecutionOrder(process.getExecutionOrder());
                    productionProcess.setProcessName(process.getProcessName());
                    productionProcess.setResponsiblePerson(process.getResponsiblePerson());
                    productionProcess.setBillingMethod(process.getBillingMethod());
                    productionProcess.setLaborCost(process.getLaborCost());
                    productionProcess.setRequiredCost(process.getRequiredCost());
                    productionProcess.setPlannedCompletionDate(process.getPlannedCompletionDate());
                    productionProcess.setRemarks(process.getRemarks());
                    productionProcessMapper.insert(productionProcess);
                }
            }
            responseInfo.code = 200;
            responseInfo.data = "更新成功";
            return responseInfo;

        } catch (Exception e) {
            throw e;
        }
    }

    public BaseResponseInfo getMaterialByTaskId(Long taskId) {
        BaseResponseInfo responseInfo = new BaseResponseInfo();
        try {
            List<BomMaterialVo> materialList = productionMaterialMapper.getMaterialByTaskId(taskId);
            responseInfo.code = 200;
            responseInfo.data = materialList;
        } catch (Exception e) {
            e.printStackTrace();
            responseInfo.code = 500;
            responseInfo.data = "查询失败：" + e.getMessage();
        }
        return responseInfo;
    }

    public BaseResponseInfo getProcessByTaskId(Long taskId) {
        BaseResponseInfo responseInfo = new BaseResponseInfo();
        try {
            LambdaQueryWrapper<ProductionProcess> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProductionProcess::getProductionOrderId, taskId);
            wrapper.eq(ProductionProcess::getDeleteFlag, "0");
            List<ProductionProcess> processList = productionProcessMapper.selectList(wrapper);
            responseInfo.code = 200;
            responseInfo.data = processList;
        } catch (Exception e) {
            e.printStackTrace();
            responseInfo.code = 500;
            responseInfo.data = "查询失败：" + e.getMessage();
        }
        return responseInfo;
    }


    public BaseResponseInfo delete(Long[] ids) {
        BaseResponseInfo responseInfo = new BaseResponseInfo();
        try {
            productionOrderMapper.deleteBatchIds(Arrays.asList(ids));
            productionMaterialMapper.delete(new LambdaQueryWrapper<ProductionMaterial>().in(ProductionMaterial::getProductionOrderId, ids));
            productionProcessMapper.delete(new LambdaQueryWrapper<ProductionProcess>().in(ProductionProcess::getProductionOrderId, ids));
            responseInfo.code = 200;
            responseInfo.data = "删除成功";
        } catch (Exception e) {
            e.printStackTrace();
            responseInfo.code = 500;
            responseInfo.data = "删除失败：" + e.getMessage();
        }
        return responseInfo;
    }
}
